package cn.hallele.bbts.crawler.service.actions.unionlotto.processor;

import cn.hallele.bbts.crawler.common.constants.CCConstant;
import cn.hallele.bbts.crawler.common.enums.LotteryTypeEnum;
import cn.hallele.bbts.crawler.service.bo.LotteryDataBO;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Json;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * UnionLottoProcessor
 *
 * @author anle5
 * @since 2023/12/3 星期日 12:55
 */
@Slf4j
public class UnionLottoProcessor implements PageProcessor {
    /**
     * Processes the page, extract URLs to fetch, extract the data and store.
     *
     * @param page page
     */
    @Override
    public void process(Page page) {
        Json json = page.getJson();
        JSONObject jsonObject = (JSONObject) JSONUtil.parse(json.get());
        JSONArray jsonArray = jsonObject.getJSONArray("result");

        List<LotteryDataBO> lotteryDataBOS = new ArrayList<>(jsonArray.size());
        jsonArray.forEach(e -> {
            JSONObject jsonResult = (JSONObject) e;
            lotteryDataBOS.add(LotteryDataBO.builder()
                    .issueId(jsonResult.getStr("code"))
                    .lotteryType(LotteryTypeEnum.UNION_LOTTO)
                    .salesAmount(Long.parseLong(jsonResult.getStr("sales").replace("_", "0")))
                    .totalAmount(Long.parseLong(jsonResult.getStr("poolmoney").replace("_", "0")))
                    .drawDate(LocalDate.parse(jsonResult.getStr("date").replace("(", "(周"), DateTimeFormatter.ofPattern("yyyy-MM-dd(E)")).atStartOfDay())
                    .winningNumbers(jsonResult.getStr("red") + "|" + jsonResult.getStr("blue"))
                    .build());
        });
        page.getResultItems().put(CCConstant.PIPELINE_RESULT, lotteryDataBOS);
    }
}
